<template>
  <div class="contiaer">
    <div class="videobox">
      <div class="title-plaer">视频流</div>
      <div class="local-player" ref="localPlayerRef"></div>
      <!-- 远程用户： -->
      <!-- <div class="remote-user" v-if="formData.role == 'audience'" ref="remoteUserRef"></div> -->
    </div>
    <Information
      @joinStart="joinStart"
      @leaveChannel="leaveChannel"
      @getRoomInfo="getRoomInfo(false)"
      :isJoin="isJoin"
      :localUser="localUser"
      :roomData="roomData"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, reactive, watch } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Cookies from "js-cookie";
import Information from "./information.vue";
import AgoraRTC from "agora-rtc-sdk-ng";
import { useOptionsStore } from "@/store/options";
import { useRouter, useRoute } from "vue-router";
import { useSSE } from "@/js/useSSE.js";
import { roomInfo, seeToken } from "@/js/api.js";
import { SSE } from "sse.js";

const router = useRouter();
const route = useRoute();

const isProduction = import.meta.env.PROD;
const token = Cookies.get("authToken");
if (!token) {
  ElMessageBox.alert("登入过期，请重新登入", "提示", {
    confirmButtonText: "确定",
    callback: (action) => {
      router.replace({ name: "Home" });
    },
  });
}

const localUser = reactive({
  videoTrack: null,
  audioTrack: null,
});

let client = AgoraRTC.createClient({ mode: "live", codec: "vp8" });
const localPlayerRef = ref(null);
const remoteUserRef = ref(null);
const remoteUsers = ref([]);
const formData = ref({});
const isJoin = ref(false);
const closeSSE = ref({});
const isConnected = ref(false);

const store = useOptionsStore();

const { options } = store;
const { uid, channel, role } = route.query;

onBeforeUnmount(() => {
  leaveChannel();
});

const roomData = ref({});
const sseData = ref({});
const getRoomInfo = (sseBol = true) => {
  roomInfo().then((res) => {
    if (res.code == 200) {
      roomData.value = res.data;
      if (sseBol) SSEInfo();
    }
  });
};

const SSEInfo = async () => {
  const tokenRes = await seeToken();


  let SSEAPI = "http://120.55.183.212:5050/room/sse/anchor/connect"
  let es = new SSE(`${SSEAPI}?token=${tokenRes.data.token}`, {
    headers: {},
    payload: null,
    method: "GET",
    autoReconnect: true,
    reconnectDelay: 3000, // 重连间隔
    maxRetries: Infinity, // 最大重试次数
    useLastEventId: true,
  });

  es.addEventListener("open", () => {
    isConnected.value = true;
  });

  es.addEventListener("message", (e) => {
    let payload = e.data;
    try {
      payload = JSON.parse(e.data);
    } catch {}
    sseData.value = payload;
  });

  es.addEventListener(roomData.value.roomId, (e) => {

  
    let payload = e.data;
    try {
      payload = JSON.parse(e.data);
    } catch {}
    sseData.value = payload;
    if (payload?.msgType) {
      if (!["system:tips", "game:nextRound", "game:settle"].includes(payload.msgType)) {
        getRoomInfo(false);
      } else if (payload.msgType == "system:tips") {
        ElMessageBox.alert(payload.info, "提示", {
          confirmButtonText: "确定",
          callback: (action) => {},
        });
      }
    }
  });

  es.addEventListener("error", (e) => {
    isConnected.value = false;
  });
  closeSSE.value = {
    close() {
      if (es) es.close();
      isConnected.value = false;
    },
  };
};
const joinChannel = async (datap) => {
  // role 角色。"audience"：观众, "host"：主播
  client.setClientRole(datap.role);
  await client.join(datap.appId, datap.channelName, datap.token, datap.anchorAgoraUid);
};

const createTrack = async () => {
  // 创建并发布本地音频和视频轨道
  // localUser.audioTrack = await AgoraRTC.createMicrophoneAudioTrack();
  // localUser.videoTrack = await AgoraRTC.createCameraVideoTrack();
  const [microphoneTrack, cameraTrack] = await AgoraRTC.createMicrophoneAndCameraTracks();
  localUser.audioTrack = microphoneTrack;
  localUser.videoTrack = cameraTrack;
  await client.publish([microphoneTrack, cameraTrack]);
  localUser.videoTrack.play(localPlayerRef.value);
  isJoin.value = true;
};

const leaveChannel = async () => {
  leaveApi();
  localUser.audioTrack && localUser.audioTrack.close();
  localUser.videoTrack && localUser.videoTrack.close();

  // 离开频道
  if (client) await client.leave();
  // 返回首页
  localPlayerRef.value = null;
  remoteUserRef.value = null;
  localUser.audioTrack = null;
  localUser.videoTrack = null;
  isJoin.value = false;

  if (closeSSE.value?.close) {
    closeSSE.value.close();
  }
};

const leaveApi = async () => {};

const handleUserPublished = async (user, mediaType) => {
  await client.subscribe(user, mediaType);
  // 如果是视频轨道，则添加到远程用户列表
  if (mediaType === "video") {
    user.videoTrack.play(localPlayerRef.value);
  }
  // 如果是音频轨道，直接播放
  if (mediaType === "audio") {
    user.audioTrack.play();
  }
  isJoin.value = true;
};

const handleUserUnpublished = (user) => {
  // 移除远程用户
  remoteUsers.value = remoteUsers.value.filter((remoteUser) => remoteUser.uid !== user.uid);
};
const joinStart = async (val) => {
  formData.value = val;
  await joinChannel(val);
  if (val.role == "audience") {
    // 监听远程用户发布事件
    client.on("user-published", handleUserPublished);
    client.on("user-unpublished", handleUserUnpublished);
  }
  if (val.role == "host") {
    await createTrack();
    getRoomInfo();
  }
};
// leaveApi();
getRoomInfo();
</script>
<style scoped>
.title-plaer {
  height: 24px;
  line-height: 24px;
  padding: 8px 16px;
  font-size: 16px;
  background: #f8f8f8;
}
.contiaer {
  /* padding-top: 30px; */
  display: flex;
  justify-content: center;
  background: #f2f7f8;
  height: 100vh;
  background-image: url("../../assets/background.png");
  background-size: 150% 200%;
}
.videobox {
  background: #fff;
  border: 1px solid #cccccc;
  border-radius: 10px;
  width: 640px;
  height: 520px;
  overflow: hidden;
  margin-top: 30px;
}
.local-player,
.remote-user {
  width: 640px;
  height: 480px;
}
</style>
